package client_package;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.sound.sampled.*;

import client_package.Controleur.StatutSound;

public class ThreadListenerSound implements Runnable {
	private Controleur c;
	private AudioFormat format;
	
	
	public ThreadListenerSound(Controleur c) {
		this.c = c;
	    format = c.getAudioFormat();
	}
	
	public void run() {
		//System.out.println("Listening for incoming sound");
        DataLine.Info speakerInfo = new DataLine.Info(SourceDataLine.class, format);
        SourceDataLine speaker;
		try {
			speaker = (SourceDataLine) AudioSystem.getLine(speakerInfo);
			speaker.open(format);
			speaker.start();
        

            while(c.getStatutSound().equals(StatutSound.Ecoute)) { 
            	//System.out.println("je suis au debut de la boucle !");
            	byte[] voice = new byte[1024];
                c.getIn_sound().read(voice, 0, 1024);
                ByteArrayInputStream bais = new ByteArrayInputStream(voice);
                AudioInputStream ais = new AudioInputStream(bais,format,voice.length);
                int numBytesRead = 0;
                if ((numBytesRead = ais.read(voice)) != -1) speaker.write(voice, 0, numBytesRead);
                ais.close();
                bais.close();
                //System.out.println("je suis à la fin de la boucle !");
            }
            speaker.drain();
            speaker.close();
            //System.out.println("Stopped listening for incoming sound");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (LineUnavailableException e1) {
			e1.printStackTrace();
		}
	}
}